package errors

import (
	"strings"

	"github.com/go-playground/validator/v10"
)

// 按模块组织字段名称映射到中文
var fieldNameMapByModule = map[string]map[string]string{
	// 用户模块
	"user": {
		"Username":    "用户名",
		"Password":    "密码",
		"Email":       "邮箱",
		"Nickname":    "昵称",
		"Avatar":      "头像",
		"OldPassword": "旧密码",
		"NewPassword": "新密码",
		"Role":        "角色",
		"Status":      "用户状态",
	},
	// 文章模块
	"article": {
		"Title":      "文章标题",
		"Content":    "文章内容",
		"Slug":       "文章标识",
		"Summary":    "摘要",
		"CoverImage": "封面图片",
		"CategoryID": "分类",
		"ID":         "ID",
		"Status":     "文章状态",
		"Tags":       "标签",
	},
	// 书籍模块
	"book": {
		"Title":        "书名",
		"Author":       "作者",
		"Description":  "描述",
		"ISBN":         "ISBN号",
		"PublishDate":  "出版日期",
		"PageCount":    "页数",
		"Publisher":    "出版社",
		"CategoryID":   "分类",
		"Status":       "书籍状态",
		"Cover":        "封面",
		"Slug":         "书籍标识",
		"Price":        "价格",
		"Tags":         "标签",
		"ChapterCount": "章节数",
		"ReadCount":    "阅读数",
		"StarCount":    "收藏数",
		"LikeCount":    "点赞数",
	},
	// 自定义页面模块
	"page": {
		"Title":       "页面标题",
		"Slug":        "页面别名",
		"Content":     "页面内容",
		"Description": "页面描述",
		"Status":      "页面状态",
	},
	// 分类模块
	"category": {
		"Name":        "分类名称",
		"Slug":        "分类标识",
		"Type":        "分类类型",
		"ParentID":    "父分类",
		"Description": "分类描述",
		"Order":       "排序值",
		"Status":      "分类状态",
	},
	// 标签模块
	"tag": {
		"Name":        "标签名称",
		"Slug":        "标签标识",
		"Type":        "标签类型",
		"Description": "标签描述",
		"SourceIDs":   "源标签ID列表",
		"TargetID":    "目标标签ID",
		"IDs":         "标签ID列表",
	},
	// 导航模块
	"navigation": {
		"Name":        "导航名称",
		"URL":         "链接地址",
		"Icon":        "图标",
		"Position":    "导航位置",
		"Order":       "排序值",
		"Status":      "导航状态",
		"Target":      "打开方式",
		"Description": "导航描述",
		"ParentID":    "父级导航",
	},
}

// 合并所有模块的字段名映射，用于向后兼容和快速查找
var fieldNameMap = mergeFieldNameMaps()

// 合并所有模块的字段名映射
func mergeFieldNameMaps() map[string]string {
	merged := make(map[string]string)

	// 按照优先级顺序添加，后添加的会覆盖先添加的
	// 可以调整模块顺序来控制冲突时的优先级
	modules := []string{"user", "article", "book", "page", "category", "tag", "navigation"}

	for _, module := range modules {
		if moduleMap, exists := fieldNameMapByModule[module]; exists {
			for field, name := range moduleMap {
				merged[field] = name
			}
		}
	}

	return merged
}

// 验证标签映射到中文错误消息
var validationTagMap = map[string]string{
	"required": "不能为空",
	"min":      "长度不能少于%s个字符",
	"max":      "长度不能超过%s个字符",
	"email":    "格式不正确",
	"url":      "URL格式不正确",
	"numeric":  "必须是数字",
	"alpha":    "只能包含字母",
	"alphanum": "只能包含字母和数字",
}

// 字段验证错误码映射，结构为: 模块 -> 字段名 -> 验证标签 -> 错误码
var fieldErrorCodeMapByModule = map[string]map[string]map[string]int{
	// 用户模块字段验证
	"user": {
		"Username": {
			"required": ErrCodeUsernameRequired,
			"min":      ErrCodeUsernameMinLength,
			"max":      ErrCodeUsernameMaxLength,
		},
		"Email": {
			"required": ErrCodeEmailRequired,
			"email":    ErrCodeEmailFormat,
		},
		"Password": {
			"required": ErrCodePasswordRequired,
			"min":      ErrCodePasswordMinLength,
			"max":      ErrCodePasswordMaxLength,
		},
		"OldPassword": {
			"required": ErrCodeOldPasswordRequired,
		},
		"NewPassword": {
			"required": ErrCodeNewPasswordRequired,
		},
		"Nickname": {
			"max": ErrCodeNicknameMaxLength,
		},
		"Avatar": {
			"max": ErrCodeAvatarMaxLength,
		},
		"Role": {
			"required": ErrCodeRoleRequired,
		},
	},
	// 文章模块字段验证
	"article": {
		"Title": {
			"required": ErrCodeArticleTitleRequired,
			"max":      ErrCodeArticleTitleMaxLength,
		},
		"Slug": {
			"required": ErrCodeArticleSlugRequired,
			"max":      ErrCodeArticleSlugMaxLength,
		},
		"ID": {
			"required": ErrCodeArticleIDRequired,
		},
		"Status": {
			"required": ErrCodeArticleStatusRequired,
		},
		"Summary": {
			"max": ErrCodeArticleSummaryMaxLength,
		},
		"CoverImage": {
			"max": ErrCodeArticleCoverMaxLength,
		},
	},
	// 书籍模块字段验证
	"book": {
		"Title": {
			"required": ErrCodeBookTitleRequired,
			"max":      ErrCodeBookTitleMaxLength,
		},
		"Author": {
			"required": ErrCodeBookAuthorRequired,
			"max":      ErrCodeBookAuthorMaxLength,
		},
		"Description": {
			"max": ErrCodeBookDescriptionMaxLength,
		},
		"Cover": {
			"max": ErrCodeBookCoverMaxLength,
		},
		"Slug": {
			"required": ErrCodeBookSlugRequired,
			"max":      ErrCodeBookSlugMaxLength,
		},
		"CategoryID": {
			"required": ErrCodeBookCategoryRequired,
		},
		"Status": {
			"required": ErrCodeBookStatusInvalid,
		},
		"ISBN": {
			"max": ErrCodeBookISBNMaxLength,
		},
	},
	// 自定义页面模块字段验证
	"page": {
		"Title": {
			"required": ErrCodePageTitleRequired,
			"max":      ErrCodePageTitleMaxLength,
		},
		"Slug": {
			"required": ErrCodePageSlugRequired,
			"max":      ErrCodePageSlugMaxLength,
		},
		"Content": {
			"required": ErrCodePageContentRequired,
		},
	},
	// 分类模块字段验证
	"category": {
		"Name": {
			"required": ErrCodeCategoryNameRequired,
			"max":      ErrCodeCategoryNameMaxLength,
		},
		"Slug": {
			"required": ErrCodeCategorySlugRequired,
			"max":      ErrCodeCategorySlugMaxLength,
		},
		"Type": {
			"required": ErrCodeCategoryTypeRequired,
			"oneof":    ErrCodeCategoryTypeInvalid,
		},
		"Description": {
			"max": ErrCodeCategoryDescMaxLength,
		},
		"Status": {
			"oneof": ErrCodeCategoryStatusInvalid,
		},
		"Order": {
			"min": ErrCodeCategoryOrderInvalid,
		},
	},
	// 标签模块字段验证
	"tag": {
		"Name": {
			"required": ErrCodeTagNameRequired,
			"max":      ErrCodeTagNameMaxLength,
		},
		"Slug": {
			"required": ErrCodeTagSlugRequired,
			"max":      ErrCodeTagSlugMaxLength,
		},
		"Type": {
			"required": ErrCodeTagTypeRequired,
			"oneof":    ErrCodeTagTypeInvalid,
		},
		"Description": {
			"max": ErrCodeTagDescriptionLength,
		},
		"SourceIDs": {
			"required": ErrCodeTagSourceIDsRequired,
		},
		"TargetID": {
			"required": ErrCodeTagTargetIDRequired,
		},
		"IDs": {
			"required": ErrCodeTagIDsRequired,
		},
	},
	// 导航模块字段验证
	"navigation": {
		"Name": {
			"required": ErrCodeNavigationNameRequired,
			"max":      ErrCodeNavigationNameMaxLength,
		},
		"URL": {
			"required": ErrCodeNavigationURLRequired,
			"url":      ErrCodeNavigationURLMaxLength,
		},
		"Icon": {
			"max": ErrCodeNavigationIconMaxLength,
		},
		"Position": {
			"required": ErrCodeNavigationPositionRequired,
			"oneof":    ErrCodeNavigationPositionInvalid,
		},
		"Order": {
			"min": ErrCodeNavigationBatchOrderFailed,
		},
		"Status": {
			"oneof": ErrCodeNavigationStatusInvalid,
		},
		"Target": {
			"oneof": ErrCodeNavigationTargetMaxLength,
		},
		"Description": {
			"max": ErrCodeNavigationDescriptionLength,
		},
		"ParentID": {
			"min": ErrCodeNavigationParentNotFound,
		},
	},
}

// 获取字段对应的错误码
func getFieldErrorCode(fieldName, tagName string) int {
	// 按照优先级顺序查找，找到第一个匹配的就返回
	// 可以调整模块顺序来控制冲突时的优先级
	modules := []string{"user", "article", "book", "page", "category", "tag", "navigation"}

	for _, module := range modules {
		if moduleMap, exists := fieldErrorCodeMapByModule[module]; exists {
			if fieldMap, exists := moduleMap[fieldName]; exists {
				if errCode, exists := fieldMap[tagName]; exists && errCode > 0 {
					return errCode
				}
			}
		}
	}

	return 0 // 未找到匹配的错误码
}

// ParseValidationError 解析验证错误，返回友好的中文错误消息
// 输入为validator.ValidationErrors类型的错误，输出为字段映射到错误消息的map
func ParseValidationError(err error) AppError {
	// 尝试转换为ValidationErrors
	if valErrs, ok := err.(validator.ValidationErrors); ok {
		fieldErrors := make(map[string]int)
		fieldMessages := make(map[string]string)

		for _, e := range valErrs {
			fieldName := e.Field()
			tagName := e.Tag()

			// 查找错误码
			errCode := getFieldErrorCode(fieldName, tagName)
			if errCode > 0 {
				fieldErrors[fieldName] = errCode
				fieldMessages[fieldName] = GetErrorMessage(errCode)
			} else {
				// 找不到特定错误码，生成通用错误消息
				chineseFieldName := fieldNameMap[fieldName]
				if chineseFieldName == "" {
					chineseFieldName = fieldName
				}

				errMsg, exists := validationTagMap[tagName]
				if !exists {
					errMsg = "验证失败"
				}

				// 替换错误消息中的参数
				if strings.Contains(errMsg, "%s") && e.Param() != "" {
					errMsg = strings.Replace(errMsg, "%s", e.Param(), 1)
				}

				fieldMessages[fieldName] = chineseFieldName + errMsg
			}
		}

		// 如果找到了错误码，使用ValidationErrors方法
		if len(fieldErrors) > 0 {
			return ValidationErrors(fieldErrors)
		}

		// 否则，返回通用验证错误
		return New(ErrCodeValidation, "请求参数验证失败").WithDetails(map[string]interface{}{
			"fields": fieldMessages,
		})
	}

	// 处理JSON格式错误
	errMsg := err.Error()
	if strings.Contains(errMsg, "invalid character") ||
		strings.Contains(errMsg, "unexpected end of JSON input") ||
		strings.Contains(errMsg, "cannot unmarshal") {
		return JSONFormatError()
	}

	// 其他类型的错误，作为通用系统错误处理
	return Wrap(err, ErrCodeSystem, "")
}

// ParseRequestBodyError 解析请求体错误，识别常见错误类型并返回友好错误
func ParseRequestBodyError(err error) AppError {
	errMsg := err.Error()

	// 验证错误
	if strings.Contains(errMsg, "validation") || strings.Contains(errMsg, "binding") {
		return ParseValidationError(err)
	}

	// JSON格式错误
	if strings.Contains(errMsg, "invalid character") ||
		strings.Contains(errMsg, "unexpected end of JSON input") ||
		strings.Contains(errMsg, "cannot unmarshal") {
		return JSONFormatError()
	}

	// 其他错误
	return Wrap(err, ErrCodeSystem, "")
}
